package com.qw.flutter.thirdlogin.qq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.qw.flutter.thirdlogin.R;
import com.qw.flutter.thirdlogin.util.LogUtils;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;


/**
 * @date: 2021/5/14 13:51
 * @author: lixu
 * @description: QQ登录封装, 直接接入QQ开放平台
 * https://wiki.open.qq.com/index.php?title=Android_SDK%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA
 */
public class QQLoginWrapper implements PluginRegistry.ActivityResultListener, IUiListener {
    private static final String TAG = "QQLoginWrapper";
    private Handler handler;
    private MethodChannel.Result result;

    public static QQLoginWrapper create() {
        return new QQLoginWrapper();
    }

    /**
     * 开启QQ登录授权
     *
     * @param activity
     */
    public void startQQLoginAuth(Activity activity, ActivityPluginBinding binding, String appId, String scope, MethodChannel.Result result) {
        if (!isQQAvailable(activity)) {
            HashMap<String, Object> params = new HashMap<>(8);
            params.put("msg", activity.getString(R.string.no_install_client_tips));
            params.put("isSuccess", false);
            result.success(params);
            return;
        }

        binding.addActivityResultListener(this);
        this.handler = new Handler(Looper.getMainLooper());
        this.result = result;

        Tencent mTencent = Tencent.createInstance(appId, activity);
        //开启登录
        mTencent.login(activity, scope, this, false);
        LogUtils.i(TAG, "开启qq授权");
    }


    /**
     * 登录响应
     * {
     * "access_token": "3C4A33F254F17295C30A137939B78485",
     * "authority_cost": 6017,
     * "expires_in": 7776000,
     * "expires_time": 1585709727740,
     * "login_cost": 29,
     * "msg": "",
     * "openid": "6BF7FB84D4B168F5FDD08864F0C65536",
     * "pay_token": "E853A2D7D1A73A488B7B38288B1507ED",
     * "pf": "desktop_m_qq-10000144-android-2002-",
     * "pfkey": "5b0863312563565f0a78fdeb12ec82c1",
     * "query_authority_cost": 71,
     * "ret": 0
     * }
     *
     * @param response
     */
    @Override
    public void onComplete(Object response) {
        LogUtils.i(TAG, "qq login onComplete");
        if (result != null) {
            QQAuthBean event = new QQAuthBean();
            if (response == null) {
                event.setMsg("授权失败[-1]");
            } else {
                JSONObject jsonResponse = (JSONObject) response;
                if (jsonResponse.length() == 0) {
                    event.setMsg("授权失败[-2]");
                } else {
                    try {
                        LogUtils.i(TAG, "QQ login result json:" + jsonResponse.toString());

                        String accessToken = jsonResponse.getString("access_token");
                        String openId = jsonResponse.getString("openid");
                        if (TextUtils.isEmpty(accessToken) || TextUtils.isEmpty(openId)) {
                            event.setMsg("授权失败[-3]");
                        } else {
                            //授权成功
                            event.setOpenId(openId);
                            event.setAccessToken(accessToken);
                            event.setMsg("success");
                            onAuthComplete(event, true, false, false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        event.setMsg("qq auth fail, accessToken or openId is null");
                    }
                }
            }
            onAuthComplete(event, false, false, true);
        }
    }

    /**
     * 授权错误
     *
     * @param uiError
     */
    @Override
    public void onError(UiError uiError) {
        LogUtils.e(TAG, "qq login onError");
        if (result != null) {
            QQAuthBean event = new QQAuthBean("授权失败");
            if (uiError != null) {
                event.setMsg(uiError.errorMessage);
                LogUtils.e(TAG, "uiError.errorDetail:" + uiError.errorDetail);
                LogUtils.e(TAG, "uiError.errorMessage:" + uiError.errorMessage);
                LogUtils.e(TAG, "uiError.errorCode:" + uiError.errorCode);
            }
            onAuthComplete(event, false, false, true);
        }
    }

    /**
     * 取消授权
     */
    @Override
    public void onCancel() {
        LogUtils.e(TAG, " qq login onCancel");
        cancelAuth();
    }

    @Override
    public void onWarning(int i) {

    }

    /**
     * 取消授权
     */
    private void cancelAuth() {
        QQAuthBean event = new QQAuthBean("取消授权");
        onAuthComplete(event, false, true, false);
    }

    /**
     * 授权完成调用
     *
     * @param event     数据封装
     * @param isSuccess
     * @param isCancel
     * @param isFail
     */
    private void onAuthComplete(final QQAuthBean event, final boolean isSuccess,
                                final boolean isCancel, final boolean isFail) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (result != null) {
                    HashMap<String, Object> params = new HashMap<>(8);
                    params.put("msg", event.getMsg());

                    if (isSuccess) {
                        params.put("openId", event.getOpenId());
                        params.put("accessToken", event.getAccessToken());
                        params.put("isSuccess", true);

                    } else if (isCancel) {
                        params.put("isSuccess", false);
                    } else {
                        params.put("isSuccess", false);
                    }

                    result.success(params);
                    result = null;
                }
            }
        });
    }

    /**
     * 判断是否安装QQ客户端
     *
     * @param context
     * @return
     */
    private static boolean isQQAvailable(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equalsIgnoreCase("com.tencent.qqlite")
                            || pn.equalsIgnoreCase("com.tencent.mobileqq")
                            || pn.equalsIgnoreCase("com.tencent.tim")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d(TAG, "onActivityResult " + requestCode + " resultCode=" + resultCode);
        if (requestCode == Constants.REQUEST_LOGIN && resultCode == Activity.RESULT_CANCELED) {
            //取消授权
            LogUtils.e(TAG, "取消授权");
            cancelAuth();
        } else if (requestCode == Constants.REQUEST_LOGIN) {
            //授权成功
            Tencent.onActivityResultData(requestCode, resultCode, data, this);
        }
        return false;
    }

}
